package com.yyn.pigeon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.yyn.pigeon.entity.Goods;
import com.yyn.pigeon.entity.OrderDetail;
import com.yyn.pigeon.entity.Orders;
import com.yyn.pigeon.entity.ShoppingCart;
import com.yyn.pigeon.mapper.OrderDetailMapper;
import com.yyn.pigeon.mapper.OrdersMapper;
import com.yyn.pigeon.mapper.ShoppingCartMapper;
import com.yyn.pigeon.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyn.pigeon.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author yyn
 * @since 2023-03-16
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
private OrdersMapper ordersMapper;
@Autowired
private ShoppingCartMapper shoppingCartMapper;
@Autowired
private OrderDetailMapper orderDetailMapper;
    @Override
    public List<OrderDetail> toOrders(String userId) {
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        ordersMapper.selectList(ordersLambdaQueryWrapper);
//        找到该用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(null);
//        创一个订单
        Orders orders = new Orders();
        orders.setNumber(String.valueOf(IdWorker.getId()));//订单号为随机
        orders.setUserId(Long.valueOf(userId));
        ordersMapper.insert(orders);
//        把购物车里的商品都绑定上这个订单号
        shoppingCarts.stream().map(item ->{//把订单号和菜品对应起来
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            orderDetail.setDishId(item.getGoodsId());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            orderDetailMapper.insert(orderDetail);
            return item;
        }).collect(Collectors.toList());
//        通过订单id找到下面的所有商品然后展示
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
        return orderDetails;
    }
}
